<template>
<!--这个是修改过的，原版链接 https://ext.dcloud.net.cn/plugin?id=1533 -->
<view>
  <!-- 搜索框 -->
  <view class="search_view">
    <view class="search">
      <image :src="imgPrefix('/static/image/icon/search_icon.png')"></image>
      <input type="text" placeholder="请输入城市名称" placeholder-style="font-size:26rpx" :value="inputValue" @input="bindinputCitys" />
    </view>
  </view>
  <!-- 搜索列表 -->
  <view class="list" v-if="search">
    <block v-show="searchList.length>0">
      <view class="text" v-for="item in searchList" :key="item.id" @tap.stop="bindCity(item)" :data-city="item.name" v-html="searchHighlight(item.name)"></view>
    </block>
    <view v-show="searchList.length==0" class="un_find_city">
      找不到该城市~
    </view>
  </view>
  <block v-else>
    <!-- 当前定位 -->
    <view class="location" v-if="location">
      <view class="location_address onelist-hidden">
        当前定位：
        <text class="location_city">{{ addressStr }}</text>
      </view>
      <view class="again_loaction_view" @tap.stop="againLocation">
        <image class="loaction_icon" :src="imgPrefix('/static/image/icon/loaction_icon.png')"></image>
        <text class="again_loaction_text">重新定位</text>
      </view>
    </view>
    <!-- 热门城市 -->
    <view class="hot" v-if="hot">
      <view class="hot_title">热门城市</view>
      <view class="hot_city_list">
        <view v-for="(item,index) in hotList" :key="index" @tap.stop="bindCity(item)" :data-city="item.name" :class="[hotIndex==index?'active':'']">{{ item.name }}</view>
      </view>
    </view>
    <!-- 首字母检索 -->
    <view class="searchLetter touchClass">
      <!-- 右边字母数据数据 触摸事件-->
      <view v-for="item in searchLetter" :key="item.name" :data-letter="item.name" :style="{ height: `${itemH}px` }" @touchstart.stop="searchStart" @touchmove.stop="searchMove" @touchend.stop="searchEnd">
        {{ item.name }}
      </view>
    </view>
    <!-- 左边字母跟右边字母true时 屏幕中心显示选中的首字母-->
    <!-- 居中首字母样式 -->
    <view class="cont_Letter" v-if="isShowLetter">{{ showLetter }}</view>
    <!-- <scroll-view scroll-y="true" style="height: calc(100vh - 538rpx)" :scroll-top="scrollTop" v-if="!search"> -->
    <scroll-view scroll-y="true" :style="{ height: `${winHeight}px` }" :scroll-top="scrollTop" v-if="!search" :scroll-into-view="`q${showLetter}`">
      <!-- 循环城市数据 -->
      <view v-for="(value, key) in cityList" :key="key">
        <!-- 循环首字母检索信息 -->
        <view :id="`q${key}`" class="list_letter">{{ key }}</view>
        <!-- 城市ID城市名称 -->
        <view :id="`item_city_${key}${item.id}`" class="item_city" v-for="item in value" :key="item.id" :data-city="item.name" @tap="bindCity(item)">
          {{ item.name }}
        </view>
      </view>
    </scroll-view>
  </block>
</view>
</template>

<script>
import address from './citys.js';
import {
  getLocation
} from '@/static/uitls/getLocation.js';
import API from '@/static/api/index.js';
const app = getApp();
export default {
  name: 'NynCityList',
  props: {
    cityStr: { // 城市
      type: String,
      required: false,
      default: true
    },
    addressStr: { // 定位地址字符
      type: String,
      required: false,
      default: true
    },
    hot: {
      type: Boolean,
      required: false,
      default: true
    },
    location: {
      //追加的
      type: Boolean,
      required: false,
      default: true
    }
  },
  data() {
    return {
      inputValue: '',
      nowCity: '', // 当前城市 追加的
      isShowLetter: false, //拖动时，是否显示中间字母
      showLetter: 'A', //中间字母
      searchLetter: [], //字母检索列表
      itemH: 0, //字母列表的高度
      startPageY: 0, //开始拖动字母时Y坐标
      bHeight: 0,
      tHeight: 0,
      scrollTop: 0, //城市列表容器滚动条的位置
      winHeight: 0, //城市列表窗口高度
      cityList: [], //城市列表
      hotList: [], //热门列表
      hotIndex: -1,
      search: false, //是否搜索
      searchList: [] //搜索满足条件的列表
    };
  },
  watch: {
    cityStr(value, oldValue) {
      this.nowCity = value
    },
    nowCity(value, oldValue) {
      console.log('变更了', value, oldValue)
      let {
        hotList,
        hotIndex
      } = this;
      // console.log(hotList)
      let index = -1;
      for (let i = 0; i < hotList.length; i++) {
        if (index == -1 && value.indexOf(hotList[i].name) != -1) {
          index = i;
        }
      }
      this.hotIndex = index;
      console.log(this.hotIndex)
    }
  },
  created() {
    this.initList();
  },
  methods: {
    /* 列表初始化 */
    initList() {
      let searchLetter = [];
      for (let key in address.cities) {
        searchLetter.push(key);
      }
      let sysInfo = uni.getSystemInfoSync();
      let winHeight = sysInfo.windowHeight;
      //添加要匹配的字母范围值
      //更加屏幕高度设置子元素的高度
      let itemH = winHeight / searchLetter.length;
      let tempObj = [];
      for (let i = 0; i < searchLetter.length; i++) {
        let temp = {};
        temp.name = searchLetter[i];
        temp.tHeight = i * itemH;
        temp.bHeight = (i + 1) * itemH;
        tempObj.push(temp);
      }
      this.winHeight = winHeight;
      this.itemH = itemH;
      this.searchLetter = tempObj;
      this.cityList = address.cities;
      this.hotList = address.hotCities;
      // 更新城市数据
      // API.getCityList().then(res=>{
      // 	let {data}=res;
      // 	let cities = {}
      // 	for(let i in data){
      // 		let obj = [];
      // 		data[i].forEach(e=>{
      // 		obj.push({id: e.id,spell: e.pinyin,name:e.shortname})
      // 		})
      // 		cities[i]=obj;
      // 	}
      // 	// console.log(JSON.stringify(cities))
      // })
    },
    /* 搜索城市时触发 */
    bindinputCitys(e) {
      let {
        value
      } = e.detail;
      value = value.trim();
      this.inputValue = value;
      let cities = this.cityList;
      let cyits = [];
      for (let key in cities) {
        for (let i = 0; i < cities[key].length; i++) {
          if (cities[key][i].name.search(value) != -1 || cities[key][i].spell.search(value) != -1) {
            cyits.push(cities[key][i]);
          }
        }
      }
      this.search = value != '';
      this.searchList = cyits;
      // console.log(this.searchList,this.search)
    },
    /* 检索字母拖动开始 */
    searchStart(e) {
      let showLetter = e.currentTarget.dataset.letter;
      let pageY = e.touches[0].pageY;
      this.nowLetter(pageY);
      this.showLetter = showLetter;
      this.startPageY = pageY;
      this.isShowLetter = true;
    },
    /* 检索字母拖动中 */
    searchMove(e) {
      let pageY = e.touches[0].pageY;
      let startPageY = this.startPageY;
      let tHeight = this.tHeight;
      let bHeight = this.bHeight;
      if (startPageY - pageY > 0) {
        //向上移动
        if (pageY < tHeight) {
          this.nowLetter(pageY);
        }
      } else {
        //向下移动
        if (pageY > bHeight) {
          this.nowLetter(pageY);
        }
      }
    },
    /* 检索字母拖动结束 */
    searchEnd() {
      setTimeout(() => {
        this.isShowLetter = false;
      }, 1000);
    },
    /* 点击城市 */
    bindCity(item) {
      // console.log(item)
      // 向外传递这个城市
      this.$emit('bindCity', item);
    },
    nowLetter(pageY) {
      let letterData = this.searchLetter;
      let bHeight = 0;
      let tHeight = 0;
      let showLetter = '';
      for (let i = 0; i < letterData.length; i++) {
        if (letterData[i].tHeight <= pageY && pageY <= letterData[i].bHeight) {
          bHeight = letterData[i].bHeight;
          tHeight = letterData[i].tHeight;
          showLetter = letterData[i].name;
          break;
        }
      }
      this.bHeight = bHeight;
      this.tHeight = tHeight;
      this.showLetter = showLetter;
      this.startPageY = pageY;
    },

    // 重新定位
    againLocation() {
      this.showLoading('加载中');
      let _this = this;
      getLocation(
        function (res) {
          let {
            code,
            latitude,
            longitude
          } = res;
          if (code) {
            _this.nowCity = '';
            // app.globalData.userCity = ['北京市', '北京市', '东城区'];
          } else {
            console.log(latitude, longitude);
            let arr = [];
            API.reverseAddressResolution(latitude, longitude)
              .then(function (resp) {
                console.log(resp);
                try {
                  let {
                    province,
                    city,
                    district
                  } = resp.result.address_component;
                  _this.nowCity = city;
                  arr = [province, city, district];
                } catch (err) {
                  console.log(err)
                  _this.nowCity = '';
                  // arr = ['北京市', '北京市', '东城区'];
                } finally {
                  _this.regionArr = arr;
                  app.globalData.userCity = arr;
                }
              })
              .catch(err => {
                console.log(err);
                _this.nowCity = '';
                // app.globalData.userCity = ['北京市', '北京市', '东城区'];
              });
          }
          // app._log(res);
        },
        false,
        true,
        _this
      );

    },
    // 关键词高亮  （追加）
    searchHighlight(keyword) {
      return app.searchHighlight(this.inputValue, keyword, '#7F4AFF');
    }
  }
};
</script>

<style lang="scss">
.search_view {
  border-bottom: 2rpx solid #f8f8f8;
}

.search {
  background-color: #f4f4f4;
  border-radius: 36rpx;
  width: 654rpx;
  margin: 16rpx auto 24rpx;
  position: relative;

  image {
    position: absolute;
    left: 22rpx;
    top: 22rpx;
    width: 26rpx;
    height: 26rpx;
  }

  input {
    height: 72rpx;
    text-align: left;
    padding-left: 60rpx;
  }
}

/* 首字母样式 */
.searchLetter {
  position: fixed;
  right: 0;
  top: 20%;
  width: 30px;
  height: 80%;
  text-align: center;
  justify-content: center;
  display: flex;
  flex-direction: column;
  color: #666;
  background-color: transparent;
  z-index: 1;

  view {
    height: 50rpx;
  }
}

/* 右边首字母样式 */
.touchClass {
  color: #666;
  font-size: 28rpx;
}

/* 居中显示的选中首字母 */
.cont_Letter {
  background-color: #666;
  color: #fff;
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  top: 50%;
  left: 50%;
  margin: -50px;
  width: 100px;
  height: 100px;
  border-radius: 10px;
  font-size: 26px;
  z-index: 1;
}

/* 循环数据首字母检索 */
.list_letter {
  // display: flex;
  // background-color: #f8f8f8;
  // height: 30px;
  color: #2a2a2a;
  font-size: 26rpx;
  padding-left: 40rpx;
  // align-items: center;
  padding: 28rpx 40rpx 8rpx;
}

/* 城市样式 */
.item_city {
  display: flex;
  background-color: #fff;
  height: 108rpx;
  padding-left: 40rpx;
  color: #2a2a2a;
  font-size: 28rpx;
  align-items: center;
  border-bottom: 2rpx solid #f8f8f8;
}

/* 热门城市 */
.hot {
  background: #ffffff;
  display: flex;
  flex-flow: row wrap;
  padding: 48rpx 48rpx 44rpx;
  border-top: 2rpx solid #f8f8f8;

  .hot_view {
    font-size: 28rpx;
    line-height: 40rpx;
    color: #8f8f9a;
    margin-bottom: 24rpx;
  }

  .hot_title {
    font-size: 28rpx;
    color: #8f8f9a;
  }

  .hot_city_list {
    display: flex;
    flex-wrap: wrap;

    // justify-content: space-between;
    view {
      font-size: 28rpx;
      padding: 10rpx 38rpx;
      margin-top: 24rpx;
      background-color: #f8f8f7;
      border: 2rpx solid #f8f8f7;
      border-radius: 8rpx;

      &:not(:nth-child(4n)) {
        margin-right: 24rpx;
      }

      &.active {
        color: #7F4AFF;
        border: 2rpx solid #7F4AFF;
        background-color: rgba(127, 74, 255, 0.05);
      }
    }
  }
}

/* 当前定位 */
.location {
  padding: 24rpx 48rpx;
  display: flex;
  justify-content: space-between;

  &_address {
    font-size: 28rpx;
    color: #8f8f9a;

    .location_city {
      color: #252748;
    }
  }

  .again_loaction_view {
    display: flex;
    align-items: center;
    white-space: nowrap;

    .loaction_icon {
      width: 26rpx;
      height: 26rpx;
    }

    .again_loaction_text {
      padding-left: 8rpx;
      font-size: 24rpx;
      color: #7f4aff;
    }
  }
}

.list {
  width: 750rpx;
  height: 500rpx;

  .un_find_city {
    text-align: center;
    padding-top: 40rpx;
    font-size: 22rpx;
  }

  .eng {
    background: #ffffff;
    padding: 30rpx;
    color: #212121;
  }

  .text {
    line-height: 106rpx;
    color: #212121;
    font-size: 26rpx;
    margin: 0rpx 48rpx;
    border-bottom: 2rpx solid #f8f8f8;
    font-size: 28rpx;
    color: #252748;
  }
}
</style>
